package cn.powertime.evaluation.shiro.jwt;

import cn.powertime.evaluation.entity.SysUser;
import cn.powertime.evaluation.exception.LoginException;
import cn.powertime.evaluation.facade.SysUserFacade;
import cn.powertime.evaluation.shiro.exception.TokenParserException;
import cn.powertime.evaluation.vo.ShiroUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author ZYW
 */
@Component
public class SubjectUtil {

    @Autowired
    private SysUserFacade userFacade;

    @Autowired
    private TokenUtils tokenUtils;

    public Long getSubjectId() {
        try {
            return ((ShiroUserInfo) SecurityUtils.getSubject().getPrincipal()).getId();
        } catch (Exception e) {
            throw new IllegalArgumentException("该用户未登录");
        }
    }


    /**
     * 直接从token获取用户id，不抛异常。
     * @param token token
     * @return 用户id
     */
    public SysUser getSubjectIdFromToken(String token) {
        return this.getSubjectUserFromToken(token);
    }

    /**
     * 直接从token获取用户id，不抛异常。
     * @param token token
     * @return 用户id
     */
    public SysUser getSubjectUserFromToken(String token) {
        if(StringUtils.isBlank(token)){
            throw new TokenParserException("令牌为空！");
        }

        String username = this.tokenUtils.getUsernameFromToken(token);

        if (StringUtils.isBlank(username)) {
            throw new TokenParserException("从令牌中解析用户名为空！");
        }
        List<SysUser> userList = this.userFacade.selectByAccount(username);
        if (CollectionUtils.isEmpty(userList)) {
            throw new LoginException("用户不存在！");
        }
        return userList.get(0);
    }
}
